var DaogouIndexCtrl = ['$scope', '$rootScope', '$location', 'UserLoginCheck', 'ShopSetCheck', 'BaseDaoGou', 'PosUser', 'GoodsCart', 'BaseGoods', 'ngDialog','socket','shortCutAction', function ($scope, $rootScope, $location, UserLoginCheck, ShopSetCheck, BaseDaoGou, PosUser, GoodsCart, BaseGoods, ngDialog,socket,shortCutAction) {
        //登录判断
        UserLoginCheck();
        ShopSetCheck();
        //商品列表
        $scope.goodsList = [];
        /*二维数组：颜色、尺码、skus
         */
        //颜色组    //尺码组 //skus
        $scope.colors = [];
        $scope.sizes = [];
        $scope.skus = [];

        //存放购买商品
        $scope.selected_goods = {};
        //是否选中推荐商品
        var choseArr = {};
        $scope.check = {};
        //存放推荐商品
        $scope.select_recomGoods = {};
        //商品搜索关键字
        $scope.input_keywords = '';
        //左侧导航窗格开关：true隐藏、false显示
        $scope.navBox = true;
        //右侧切换导购窗格开关：true隐藏、false显示
        $scope.persBox = true;
        //商品列表页面开关：true隐藏、false显示
        $scope.goods_show = true;
        //商品详情页面开关：true隐藏、false显示
        $scope.detail = true;
		
		var configData = $api.getStorage('configData');
        //判断导购类型
        $scope.configData = $api.getStorage('configData');
        //导购员列表
        $scope.Guide = [];
        $scope.win_name ="daogou_window";
        //私有方法=================================================================
        //显示导购
        var get_daogou = function (code) {
            PosUser.get_user_by_shopCode(code).then(function (response) {
                $scope.user = response;
                $scope.Guide = response;
            }).catch(function (err) {
//              baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: err.msg});
            	baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
            });
        };

        //获取大类
        var get_category = function () {
            var cate_array = [];
            BaseDaoGou.get_category_list().then(function (response) {           
//              if (response.data.status == 1) {
//                  var data = response.data.data.data;
//                  $.each(data, function (i, n) {
////                  	if(n.is_show == 1){
//                      cate_array.push(n);
////                  	}
//                  });
//                  $scope.category = cate_array;
//              }
				//该商品大类下商品条目
				$.each(response,function(i,n){
					response[i].num = 0;
					$.each($scope.sort,function(s_i, s_n) {
						BaseDaoGou.get_num_by_cate_and_sort(n.category_code, s_n.sort_code).then(function(ret){
							num = ret[0].num;
							response[i].num += ret[0].num;
						});
					});
				});
                //从本地获取
				$scope.category = response;

            }).catch(function (err) {
//              baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: err.msg});
				baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
            });
        };

        //获取小分类 品类
        var get_sort = function () {
            var sort_array = [];
            BaseDaoGou.get_sort_list().then(function (response) {
//              if (response.data.status == 1) {
//                  var data = response.data.data.data;
//                  $.each(data, function (i, n) {
////                  	if(n.is_show == 1){
//                      sort_array.push(n);
////                  	}
//                  });
//                  $scope.sort = sort_array;
//              }
	            //从本地获取
				$scope.sort = response;

	            get_category();
            }).catch(function (err) {
//              baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: err.msg});
				baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
            });
        };

        //搜索商品(根据sku和GoodsCode)
        var search_goods = function (code) {
            var key = new String(code);
            if ('' == code || key.length < 3) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT,
                    msg: $rootScope.language.TIPS_CUNHUO_NUM_NEED
                });//'请至少输入三位'
                return false;
            }
            BaseDaoGou.get_goods_by_code(code).then(function (response) {
                if (response.length == 0) {
                    baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_CUNHUO_SEARCH_GOODS});
                    return false;
                } else {
                    	//隐藏全部
                    	$scope.allHide();
                    	//显示商品列表页
	                    $scope.goods_show = false;
	                    $scope.detail = true;
	                    $scope.goodsList = response;
                   
                }
            }).catch(function (err) {
//              baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: err.msg});
            	baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
            });
        };




        //页面效果============================================

        //左侧导航事件
        $scope.navToggle = function () {
            $scope.navBox = !$scope.navBox;
            if ($scope.navBox && $scope.persBox) {
                $scope.shade = true;
            } else {
                $scope.shade = false;
            }
            $scope.goods_show = true;
            if ($scope.navBox) {
                $scope.navAnimate = ""
            } else {
                $scope.navAnimate = "active"
            }
        }

        //左滑导航栏的关闭
        $scope.navClose = function () {
            $scope.navBox = true;
            if ($scope.navBox && $scope.persBox) {
                $scope.shade = true;
            }
            if ($scope.navBox) {
                $scope.navAnimate = ""
            } else {
                $scope.navAnimate = "active"
            }
        }
        //右侧导购
        $scope.persToggle = function () {
            $scope.persBox = !$scope.persBox;
            if ($scope.navBox && $scope.persBox) {
                $scope.shade = true;
            } else {
                $scope.shade = false;
            }
            $scope.goods_show = true;
            if ($scope.persBox) {
                $scope.persAnimate = ""
            } else {
                $scope.persAnimate = "active";
				//当前导购员：默认是登录用户
				if(typeof $scope.daogou == 'undefined'){
					$scope.daogou = $rootScope.user;
				}
                
            }
        }
        $scope.persClose = function () {
            $scope.persBox = true;
            if ($scope.navBox && $scope.persBox) {
                $scope.shade = true;
            }
            if ($scope.persBox) {
                $scope.persAnimate = ""
            } else {
                $scope.persAnimate = "active"
            }
        }


        ////////////////////////////////////////////////////////
         //获取服务器图片地址(商品展示)
        $scope.get_http_image = function (sku) {
            return configData.api_url + 'pos/image/sku&sku=' + sku;        
        };
        
        $scope.picture_array=[];
        $scope.picture_slide_switch = false;
        //商品详情
        $scope.goodsDetail = function (g) {         
            $scope._g = g;  //传过来的商品信息
            //baison_app.api.alert({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],msg:g});
            //颜色组  	//尺码组 //skus 默认为空
            $scope.colors = [];
            $scope.sizes = [];
            $scope.skus = [];
            $scope.promotions = [];  //存放促销
            //商品展示隐藏、商品详情展示
            $scope.goods_show = true;
            $scope.detail = false;

            var colorKeys = [];
            var sizeKeys = [];
             
            
            $scope.picture_array[0] = $scope.get_http_image(g.SkuCode);
            $scope.picture_array[1] = $scope.get_http_image(g.SkuCode);
            $scope.picture_array[2] = $scope.get_http_image(g.SkuCode);
//          
            //根据GoodsCode查出所有的sku(一个货号对应多个sku)
            BaseDaoGou.getSku_by_GoodCode(g.GoodsCode).then(function (response) {
          //商品详细信息
                $scope.goods = response[0];
                $scope.GoodsCode = g.GoodsCode;
                $.each(response, function (i, n) {
                    var a = {};
                    var b = {};
                    var c = {};

                    var colkey = n.ColorCode;
                    if (colorKeys.indexOf(n.ColorCode) == -1) {
                        colorKeys.push(colkey);
                        $scope.colors.push(
                                {
                                    'ColorCode': n.ColorCode,
                                    'ColorName': n.ColorName
                                }
                        );
                    }

                    var sizkey = n.SizeCode;
                    if (sizeKeys.indexOf(n.SizeCode) == -1) {
                        sizeKeys.push(sizkey);
                        $scope.sizes.push(
                                {
                                    'SizeCode': n.SizeCode,
                                    'SizeName': n.SizeName
                                }
                        );
                    }

                    a[n.ColorCode] = b;
                    b[n.SizeCode] = c;
                    c['SkuNum'] = n.SkuNum;
                    c['SkuCode'] = n.SkuCode;
                    c['GoodsName'] = n.GoodsName;
                    c['SkuPrice'] = n.SkuPrice;
                    c['SkuVipPrice'] = n.SkuVipPrice;
                    c['SkuPropertyName'] = n.SkuPropertyName;
                    c['SkuChenlie'] = n.SkuChenlie;
                    c['ColorCode'] = n.ColorCode;
                    c['SizeCode'] = n.SizeCode;
                    c['ColorName'] = n.ColorName;
                    c['SizeName'] = n.SizeName;
                    $scope.skus.push(a);
                    
                });



                //获取商品评价
                BaseDaoGou.get_comments_by_goodsCode(g.GoodsCode).then(function (ret) {
                    if (ret.data.status == 1) {
                        $scope.comments = ret.data.data;
                    }
                });
                //获取商品月销量
                BaseDaoGou.get_sales_by_day(response[0], 30).then(function (ret) {
                    //获取商品总销量
                    BaseDaoGou.get_allSales(response[0]).then(function (res) {
                        if (res[0].total_num == null) {
                            $scope.goods.total_num = 0;
                        } else {
                            $scope.goods.total_num = res[0].total_num;
                        }
                    });
                    if (ret[0].MonSales == null) {
                        $scope.goods.MonSales = 0;
                    } else {
                        $scope.goods.MonSales = ret[0].MonSales;
                    }

                });

                //获取推荐商品信息
                BaseDaoGou.getRecommendGoods(response[0]['GoodsCode']).then(function (response) {
                    //获取推荐商品的信息
                    if (Object.keys(response).length <= 0) {
                        //若没有推荐商品则不显示
                        $scope.isRec = '';
                        return;
                    } else {
                        $scope.isRec = 'true';
                        $scope.recommendGoods = response;
                    }
                });
                //获取促销信息
                BaseDaoGou.get_promotion_by_sku(response[0]['SkuCode']).then(function (ret) {
                    $.each(ret, function (i, n) {
                        if(n.remark == null){
                        	n.pro_remark = '';
                        }else{
                        	n.pro_remark = 'true';
                        }
                        $scope.promotions.push(n);
                    });
                });
            });
			
			
			//商品详情
             
			if(!$scope.picture_slide_switch){
		        
				$scope.picture_slide_switch = true;
			}
        };

        //左侧导航菜单二级点击，根据分类代码查询并显示
        $scope.goodsShow = function (category_code, sort_code) {
            //隐藏全部
           // $scope.allHide();
	        $scope.shade = true;

	        $scope.persBox = true;
	        $scope.navAnimate = "";
	        $scope.persAnimate = "";

            //显示商品列表页
            $scope.goods_show = false;
            $scope.detail = true;
	     //   console.log(category_code);

	        var Keys = [];
       	    var goods = [];
            BaseGoods.get_goods_list_by_cate(category_code, sort_code).then(function (response) { 
                if(response.length > 0){
                	$.each(response,function(i,n){
                		var goodsKey = n.GoodsCode;
	                    if (Keys.indexOf(n.GoodsCode) == -1) {
	                        Keys.push(goodsKey);
	                        goods.push(n);
	                    }
                	});
	                $scope.goodsList = goods;
	                $scope.navBox = true;
                } else {
	                $scope.goods_show = true;
	                $scope.navBox = false;
                }
                //页面里面根据is_hot:1表示热卖， 0表示非热卖
            }).catch(function (err) {
                baison_app.api.toast({title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_NOT_CONNECTED_INTERNET}); //'没有联网'
            });
        };
        //热卖商品显示
        $scope.hotGoods = function () {
            //隐藏全部
            $scope.allHide();
            //显示商品列表页
            $scope.goods_show = false;
            $scope.detail = true;
            BaseDaoGou.getHotGoods().then(function (response) {
                $scope.goodsList = response;
            }).catch(function (err) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: err.msg});
            });
        };





        //底部遮罩
        $scope.shade = true;
        $scope.allHide = function () {
            $scope.shade = true;
            $scope.navBox = true;
            $scope.persBox = true;
            $scope.navAnimate = "";
            $scope.persAnimate = "";
        }

        //左侧导航菜单一级
        $scope.lowLevel='lowLevel';
        $scope.lowToggle = function (num,category_code) {
            if($scope.lowLevel == num){
                $scope.lowLevel = 'lowLevel';
            }else{
               $scope.lowLevel = num; 
            }
            
            //显示大类和品牌的商品数量
            $.each($scope.sort,function(i,n){
                BaseDaoGou.get_num_by_cate_and_sort(category_code,n.sort_code).then(function(ret){
					n.num = ret[0].num;
				});
            });
        }

        

        //事件=================================================================
        //判断是否有显示分类的权限(不需要)
//      if($rootScope.purview['\/goods_brand'].show == 1){
//          return ;
//      }else{
		//获取商品小分类
		get_sort();
	    //获取大类
     //   get_category();

        //获取导购员
        get_daogou($rootScope.current_shop.ShopCode);
//      }
       
       

        //购物车列表
        if (!$rootScope.goods_cart) {
            GoodsCart.init();
        }

        //选中sku进行购买
        $scope.getSku = function (sku, color, size) {
            $scope.availPromotions = []; //存放对应sku可用促销
            $scope.selected_goods = sku[color][size];
            //获取促销信息
            BaseDaoGou.get_promotion_by_sku($scope.selected_goods['SkuCode']).then(function (ret) {
                $.each(ret, function (i, n) {
                    $scope.availPromotions.push(n);
                });
            });
        };


        //选中推荐商品
        $scope.check = function (index, sku, check) {
            if (check == true) {//选中
                choseArr[index] = sku;
                $scope.select_recomGoods = choseArr;
            } else {
                delete choseArr[index];
                //取消选中
                delete $scope.check[index];
                $scope.select_recomGoods = choseArr;
            }
        };
        //去结算
        $scope.buy = function (selected_goods, select_recomGoods) {
            if (Object.keys(selected_goods).length <= 0) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.MSG_WITHOUT_SELECT_GOODS});
                return;
            }
            if (selected_goods.SkuNum < 0) {
                baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_DAOGOU_INVENTORY});
                return;
            }
            if (Object.keys(select_recomGoods).length >= 1) {
                $.each(select_recomGoods, function (i, n) {
                    if (n.SkuNum < 1) {
                        baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_DAOGOU_INVENTORY});
                        return;
                    }
                    if ($rootScope.user.UserCode == '000' && typeof $scope.daogou == 'undefined') {
                        if (typeof $scope.Guide != 'undefined' && $scope.Guide.length != 0) {
                            GoodsCart.add_to_cart(n, $scope.configData.daogou, $scope.Guide[0].UserCode);
                        } else {
                            GoodsCart.add_to_cart(n, $scope.configData.daogou, "000");
                        }
                    } else if($rootScope.user.UserCode != '000'){
                        if(typeof $scope.daogou == 'undefined'){
                        	GoodsCart.add_to_cart(n, $scope.configData.daogou, $rootScope.user.UserCode);
                        }else{
                        	GoodsCart.add_to_cart(n, $scope.configData.daogou, $scope.daogou.UserCode);
                        }                     
                    }  
                });
            }
            if($rootScope.user.UserCode == '000'){
            	if(typeof $scope.daogou == 'undefined'){
            		if (typeof $scope.Guide != 'undefined' && $scope.Guide.length != 0) {
                            GoodsCart.add_to_cart(selected_goods, $scope.configData.daogou, $scope.Guide[0].UserCode);
                        } else {
                            GoodsCart.add_to_cart(selected_goods, $scope.configData.daogou, "000");
                        }
            	}else{
            		GoodsCart.add_to_cart(selected_goods,$scope.configData.daogou,$scope.daogou.UserCode);
            	}
            }else{
            	if(typeof $scope.daogou == 'undefined'){
                        	GoodsCart.add_to_cart(selected_goods, $scope.configData.daogou, $rootScope.user.UserCode);
                        }else{
                        	GoodsCart.add_to_cart(selected_goods, $scope.configData.daogou, $scope.daogou.UserCode);
                        }
            }
            $location.path('/cashier/index');
        };

        //关闭详情页面
        $scope.show_list = function () {
            $scope.goods_show = false;
            $scope.detail = true;
        };

        //切换导购员
        $scope.s_daogou = function (u) {
            //将当前导购切换,切换后的导购在商品购买之后，带到收银界面
            $scope.daogou = u;
            baison_app.api.toast({buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],title: $rootScope.language.COMMON_TITLE_HINT, msg: $rootScope.language.TIPS_GUIDE_SWITCH_GUIDE_TYPE});
        };

        //搜索商品
        $scope.search_goods = function (keywords) {
            search_goods(keywords);
        };

       
     
        var window_id = 0;
        $scope.scan = function (good) {
            var sku = good.GoodsCode+good.ColorCode+good.SizeCode;
            var date = new Date().getTime();
            var imgName = sku + date + ".png";
            var scanner = api.require('scanner');
            var src = 'file://' + api.fsDir + '/barImage/' + imgName;
            var url = 'http://m6.bs.lonsdale.cn/Admin//MoBanList/list/cartfromother_pay.html?sp=SHDEMO1509080001&g=' + sku + ',1' + '&s=GDDEMO1509110001';
            scanner.encode({
                string: url,
                save: {
                    imgPath: "fs://barImage",
                    imgName: imgName
                }
            }, function (ret, err) {
                if (ret.status) {
                    $scope.pic_src = api.fsDir + '/barImage/' + imgName;
                    //$("#img_scan").attr('src', $scope.pic_src);
                    window_id = ngDialog.open({closeByDocument: false,
                        trapFocus: false,
                        template: './html/daogou/pic.html',
                        disableAnimation: true,
                        scope: $scope
                    });
                } else {
                    api.alert({
                        msg: err.msg
                    });
                }
            });
        };

        socket.emit('add', 'zuojianghua');
        //投影到大屏幕
        $scope.touying = function(code){
            socket.emit('use', {'user_name': 'zuojianghua','goods_id':code});
        };
 
        
        $(function () {

                        //商品展示
                        var mySwiperList = new Swiper ('.swiper-container-list', {
                            pagination: '.swiper-pagination',
                            paginationClickable: true,
                            paginationHide :true,
                            slidesPerView: 3,
                            freeMode: true,
                            keyboardControl : true,
                            mousewheelControl : true,
                            observer:true,//修改swiper自己或子元素时，自动初始化swiper
                            observeParents:true,//修改swiper的父元素时，自动初始化swiper

                                          });    


                       //商品详情     
                      var mySwiper = new Swiper ('.swiper-container', {
                            pagination: '.swiper-pagination',
                            paginationClickable: true,
                            keyboardControl : true,
                            mousewheelControl : true,
                            spaceBetween : 20,
                            observer:true,//修改swiper自己或子元素时，自动初始化swiper
                            observeParents:true,//修改swiper的父元素时，自动初始化swiper                            

                      })  
                });
 		 /***快捷键部分*************/
        shortCutAction.handler('/daogou/index', 'enter', function () {
            if ($scope.win_name == 'daogou_window') {          
                $scope.search_goods($scope.input_keywords);
                $scope.$apply();
            }
        });
        //F3获取当前焦点到输入框
        shortCutAction.handler('/daogou/index', 'f3', function () {
            $scope.focus('txt_input');
            $scope.$apply();
        });
       
    }];
DaogouIndexCtrl.$injector = ['$scope', '$rootScope', '$location', 'UserLoginCheck', 'ShopSetCheck', 'BaseDaoGou', 'PosUser', 'GoodsCart', 'BaseGoods', 'ngDialog','socket','shortCutAction'];